package com.dyp.websocket.endpoint;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;

@Component
@ServerEndpoint(value="/my/websocket/{name}")
public class FirstWebSocketHandler {
    public static HashMap<String,RemoteEndpoint.Basic> remoteEdnpoints = new HashMap<>();
    @OnOpen
    public void onOpen(@PathParam("name") String name, Session session) throws IOException
    {
        System.out.println("onOpen:" + name);
        RemoteEndpoint.Basic remoteEndpoint = session.getBasicRemote();
        remoteEdnpoints.put(name, remoteEndpoint);
        session.getUserProperties().put("name", name);
    }

    @OnClose
    public void onClose(@PathParam("name") String name, Session session) throws IOException
    {
        System.out.println("onOpen:" + name);
        RemoteEndpoint.Basic remoteEndpoint = session.getBasicRemote();
        remoteEdnpoints.remove(name, remoteEndpoint);
        System.out.println(session.getUserProperties().get("name") + "close");
    }

    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("onError");
        error.printStackTrace();
    }

    @OnMessage
    public void textMessage(Session session, String msg){
        System.out.println("textMessage:" + msg);
        try{
            session.getBasicRemote().sendText("recieve " + msg);
        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void binaryMessage(Session session, ByteBuffer msg){
        System.out.println("binaryMessage:" + msg.toString());
    }

    @OnMessage
    public void pongMessage(Session session, PongMessage msg){
        System.out.println("pongMessage:" + msg.getApplicationData().toString());
    }
}
